#include "xmppcore/abstracterror.h"
#include "xmppcore/xmlwriter.h"
#include "xmppcore/protocoltranslator.h"

namespace yoohoo_xmppcore {

ErrorSharedData::ErrorSharedData() {
	applicationSpecificCondition = 0;
}

ErrorSharedData::ErrorSharedData(const ErrorSharedData& other) : QSharedData(other), applicationSpecificCondition(other.applicationSpecificCondition),
		definedCondition(other.definedCondition), text(other.text) {
}

ErrorSharedData::~ErrorSharedData() {
	if (applicationSpecificCondition != 0) {
		delete applicationSpecificCondition;
	}
}

AbstractError::AbstractError(QString definedCondition, XmlLangText text) {
	_d = new ErrorSharedData;
	_d->definedCondition = definedCondition;
	_d->text = text;
}

QString AbstractError::definedCondition() {
	return _d->definedCondition;
}

void AbstractError::setDefinedCondition(QString definedCondition) {
	_d->definedCondition = definedCondition;
}
	
XmlLangText AbstractError::text() {
	return _d->text;
}

void AbstractError::setText(XmlLangText text) {
	_d->text = text;
}

XmppObject* AbstractError::applicationSpecificCondition() {
	return _d->applicationSpecificCondition;
}

void AbstractError::setApplicationSpecificCondition(XmppObject* applicationSpecificCondition) {
	_d->applicationSpecificCondition = applicationSpecificCondition;
}

QString AbstractError::toXml() {
	XmlWriter writer;

	writeErrorHeader(&writer);

	writer.writeStartElement(_d->definedCondition);
	writer.writeNamespace(definedConditionNamespace());
	writer.writeEndElement();

	if (!_d->text.isNull()) {
		writer.writeStartElement("text");
		if (!_d->text.xmlLang().isEmpty()) {
			writer.writeAttribute("xml:lang", _d->text.xmlLang());
		}
		writer.writeNamespace(definedConditionNamespace());
		writer.writeCharacters(_d->text.text());
		writer.writeEndElement();
	}

	if (_d->applicationSpecificCondition != 0) {
		ProtocolTranslator* translator = dynamic_cast<ProtocolTranslator*>(_d->applicationSpecificCondition);
		if (translator != 0) {
			writer.writeCharacters(translator->toXml(), false);
		}		
	}

	writeErrorFooter(&writer);

	return writer.toXml();
}

}
